import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { Breadcrumb, Typography, Card, Descriptions, Tag, Button, Divider, Table, Space, message } from 'antd';
import { UserOutlined, DownloadOutlined, FileOutlined, ArrowUpOutlined, ArrowDownOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { auth, torrents } from '../../services';

const { Title, Text, Paragraph } = Typography;

const TorrentDetail = ({ setIsLoggedIn }) => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [torrent, setTorrent] = useState(null);
  const [user, setUser] = useState(null);

  const [messageApi, contextHolder] = message.useMessage();
  const [loading, setLoading] = useState(true);
  const watchAddedRef = useRef(false); // 用于防止重复调用addWatch

  useEffect(() => {
    // 当种子ID改变时重置ref，允许为新种子添加浏览量
    watchAddedRef.current = false;

    const loadData = async () => {
      try {
        console.log('🔍 TorrentDetail 开始加载数据, ID:', id);

        // 获取当前用户信息
        const userResponse = await auth.getCurrentUser();
        if (!userResponse.success || !userResponse.data?.user) {
          messageApi.error('获取用户信息失败，请重新登录');
          navigate('/login');
          return;
        }
        setUser(userResponse.data.user);

        // 获取种子详情
        console.log('📡 调用 getTorrentDetail, ID:', id);
        const torrentResponse = await torrents.getTorrentDetail(id);
        console.log('📦 getTorrentDetail 响应:', torrentResponse);

        if (!torrentResponse.success || !torrentResponse.data?.torrent) {
          console.error('❌ 获取种子信息失败:', torrentResponse);
          messageApi.error('获取种子信息失败');
          navigate('/home');
          return;
        }

        console.log('✅ 种子详情加载成功:', torrentResponse.data.torrent);
        setTorrent(torrentResponse.data.torrent);

        // 增加浏览量（不阻塞页面加载，后台静默执行）
        // 使用ref防止React StrictMode导致的重复调用
        if (!watchAddedRef.current) {
          watchAddedRef.current = true;
          try {
            await torrents.addWatch(id);
            console.log('📈 浏览量已增加');
          } catch (error) {
            console.warn('📈 浏览量增加失败（不影响页面显示）:', error);
          }
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        messageApi.error('加载数据失败: ' + error.message);
        navigate('/home');
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [id, navigate]); // 移除messageApi依赖，避免重复调用

  const handleDownload = async () => {
    if (!torrent) return;

    try {
      // 构造torrentURL，从种子对象中获取或根据ID生成
      const torrentURL = torrent.torrentUrl ||
        torrent.torrentURL ||
        torrent.tResource ||
        `torrent_file/${torrent.id}.${torrent.title || 'file'}.torrent`;

      // 确保传递种子ID给后端用于记录下载次数
      const result = await torrents.downloadTorrent(torrentURL, torrent.id);
      messageApi.success('种子文件下载成功，可直接用于uTorrent等客户端');
    } catch (error) {
      console.error('下载失败:', error);
      messageApi.error('下载失败: ' + error.message);
    }
  };



  const handleGoBack = () => {
    // 智能返回：根据浏览器历史记录返回上一页
    // 如果没有历史记录或者是直接访问，则返回资源中心
    if (window.history.length > 1) {
      navigate(-1);
    } else {
      navigate('/resources');
    }
  };

  // 智能返回按钮文本
  const getBackButtonText = () => {
    const referrer = document.referrer;
    if (referrer.includes('/resources')) {
      return '返回资源中心';
    } else if (referrer.includes('/home')) {
      return '返回首页';
    } else if (referrer.includes('/search')) {
      return '返回搜索结果';
    } else {
      return '返回上一页';
    }
  };

  if (loading) {
    return <div>加载中...</div>;
  }

  if (!torrent) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <h2>种子不存在</h2>
        <p>您访问的种子可能已被删除或不存在</p>
        <Button type="primary" onClick={() => navigate('/home')}>
          返回首页
        </Button>
      </div>
    );
  }

  if (!user) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <h2>请先登录</h2>
        <Button type="primary" onClick={() => navigate('/login')}>
          去登录
        </Button>
      </div>
    );
  }

  // 文件列表列定义
  const fileColumns = [
    {
      title: '文件名',
      dataIndex: 'name',
      key: 'name',
      render: text => <><FileOutlined /> {text}</>,
    },
    {
      title: '大小',
      dataIndex: 'size',
      key: 'size',
    }
  ];

  return (
    <div>
      {contextHolder}
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item><Link to="/home">首页</Link></Breadcrumb.Item>
        <Breadcrumb.Item><Link to="/resources">资源库</Link></Breadcrumb.Item>
        <Breadcrumb.Item>{torrent.category}</Breadcrumb.Item>
        <Breadcrumb.Item>{torrent.title}</Breadcrumb.Item>
      </Breadcrumb>

      {/* 返回按钮 */}
      <div style={{ marginBottom: 16 }}>
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={handleGoBack}
          style={{
            padding: '4px 8px',
            color: '#1890ff',
            fontSize: '14px'
          }}
        >
          {getBackButtonText()}
        </Button>
      </div>

      <Card>
        <div style={{ display: 'flex', marginBottom: 24 }}>
          <div style={{ marginRight: 24 }}>
            <Card
              cover={<img alt={torrent.title} src={torrent.coverImage} style={{ width: 300, height: 'auto' }} />}
              style={{ width: 300 }}
            />
          </div>

          <div style={{ flex: 1 }}>
            <Title level={2}>{torrent.title}</Title>

            <Space style={{ marginBottom: 16 }} wrap>
              <Tag color="blue">{torrent.category}</Tag>
              {/* 促销标签 */}
              {torrent.promotion && torrent.promotion !== 'none' && (
                <>
                  {torrent.promotion === 'double_upload' && (
                    <Tag color="green" style={{ fontWeight: 'bold' }}>⬆️ 双倍上传量</Tag>
                  )}
                  {torrent.promotion === 'free_download' && (
                    <Tag color="orange" style={{ fontWeight: 'bold' }}>🆓 下载量免费</Tag>
                  )}
                </>
              )}
              {torrent.tags && torrent.tags.map(tag => (
                <Tag key={tag}>{tag}</Tag>
              ))}
            </Space>

            <Descriptions column={2}>
              <Descriptions.Item label="大小">{torrent.size}</Descriptions.Item>
              <Descriptions.Item label="发布时间">{torrent.uploadDate}</Descriptions.Item>
              <Descriptions.Item label="发布者">{torrent.uploader}</Descriptions.Item>
              <Descriptions.Item label="下载次数">{torrent.downloads}</Descriptions.Item>
              <Descriptions.Item label="浏览次数">{torrent.views || 0}</Descriptions.Item>
              <Descriptions.Item label="做种人数">
                <Text type={torrent.seeders > 10 ? "success" : "warning"}>
                  <ArrowUpOutlined /> {torrent.seeders}
                </Text>
              </Descriptions.Item>
              <Descriptions.Item label="下载人数">
                <ArrowDownOutlined /> {torrent.leechers}
              </Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 24 }}>
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                size="large"
                onClick={handleDownload}
                style={{ width: 200 }}
              >
                下载种子
              </Button>
            </div>
          </div>
        </div>

        <Divider orientation="left">种子描述</Divider>
        <Paragraph>{torrent.description}</Paragraph>

        <Divider orientation="left">文件列表</Divider>
        <Table
          columns={fileColumns}
          dataSource={torrent.files ? torrent.files.map((file, index) => ({ ...file, key: index })) : []}
          pagination={false}
        />


      </Card>
    </div>
  );
};

export default TorrentDetail; 